package windows.treeWindow
{
import windows.*;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;

import baseitems.Base;

import windows.treeWindow.TreeItemView;
	
	import com.bit101.components.ScrollPane;
	import com.bit101.components.Window;
	
	/**
	 * иерархия объектов. дерево.
	 * @author yaempechenki@gmail.com
	 */
	public class TreeWindow extends Window
	{
		private var container:Sprite;
		private var items:Vector.<TreeItemView>;
		private var category_array:Object;
		private var scrollPanel:ScrollPane;
		private var drugMeOne:TreeItemView;
		public function TreeWindow()
		{
			title = "Tree";
			hasMinimizeButton = true;
			width = 120;
			height = 400;
			
			container = new Sprite();
			this.addEventListener(MouseEvent.CLICK, onItemsClick);
			this.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
			this.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);

			scrollPanel = new ScrollPane(this, 0, 0);
			scrollPanel.width = width;
			scrollPanel.height = height - 20;
			scrollPanel.dragContent = false;
			scrollPanel.addChild(container);
		}
		
		public function refresh():void {
			Controller.instance.getLevelsList();
			cls();
			stopAndHide();
			category_array = getCategoryArray();
			outTree(0, 0);
			
			const currentSelectId:int = Controller.instance.haveSelected ? Controller.instance.selectedObject.id:0;
			for (var i:int = 0; i < items.length; i++) 
			{
				items[i].selected = (items[i].id == currentSelectId);
			}
			
			scrollPanel.update();
		}
		
		private function cls():void {
			while (container.numChildren > 0) {
				container.removeChildAt(0);
			}
			
			if (items) {
				for (var i:int = 0; i < items.length; i++) {
					items[i] = null;
				}
			}
			items = new Vector.<TreeItemView>;
		}
		
		private function outTree(parent_id:int, level:int):void {
			if (category_array[parent_id]) { //Если категория с таким parent_id существует
				for each (var value:Object in category_array[parent_id]) { //Обходим
					// выводим
					var one:TreeItemView = new TreeItemView(value.id_node, value.title);
					one.x = level * 12 + 5;
					one.y = 12 * items.length + 5;
					container.addChild(one);
					items.push(one);
					level++; // Увеличиваем уровень вложености
					outTree(value.id_node, level);
					level--; // Уменьшаем уровень вложености
				}
			}
		}
		
		private function getCategoryArray():Object {
			var category_array:Object = {};
			var items:Vector.<Base> = Controller.instance.getItems();
			for each (var item:Base in items) {
				var parent_id:int = 0;
				if (item.selfParent) parent_id = item.selfParent.id;
				if (!category_array[parent_id]) {
					category_array[parent_id] = [];
				}
				category_array[parent_id].push({ 'id_node':item.id, 'id_parent':parent_id, 'title':item.name });
			}
			return category_array;
		}
		
		private function onItemsClick(event:MouseEvent):void {
			if (event.target is TreeItemView) {
				var one:TreeItemView = event.target as TreeItemView;
				setSelectItem(one.id);
			}
		}
		
		private function setSelectItem(id:int):void {
			for each (var item:TreeItemView in items)
			{
				item.selected = (item.id == id);
			}
			var oneItem:Base = Controller.instance.getItemById(id);
			if (oneItem) {
				Controller.instance.selectedObject = oneItem;
			}
		}
		
		private function onMouseDown (event:MouseEvent):void {
			if (event.target is TreeItemView) {
				var one:TreeItemView = event.target as TreeItemView;
				var oneItem:Base = Controller.instance.getItemById(one.id);
				
				drugMeOne = new TreeItemView(oneItem.id, oneItem.name);
				addChild(drugMeOne);
				drugMeOne.visible = true;
				drugMeOne.startDrag(true);
			}
		}
		
		private function onMouseUp (event:MouseEvent):void {
			if (!drugMeOne) return;
			if (event.target is TreeItemView) {
				var one:TreeItemView = event.target as TreeItemView;
				var oneItem:Base = Controller.instance.getItemById(one.id);
				if(oneItem.id!=drugMeOne.id) {
					var twoItem:Base = Controller.instance.getItemById(drugMeOne.id);
					twoItem.selfParent = oneItem;
					dispatchEvent(new MouseEvent(MouseEvent.CLICK));
				}
			} else {
				// выкинуть в корень
				var secondItem:Base = Controller.instance.getItemById(drugMeOne.id);
				secondItem.selfParent = null;
				dispatchEvent(new MouseEvent(MouseEvent.CLICK));
			}
			
			stopAndHide();
		}
		
		private function stopAndHide():void {
			if (drugMeOne) {
				drugMeOne.stopDrag();
				drugMeOne.parent.removeChild(drugMeOne);
				drugMeOne = null;
			}
		}
	}
}